/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.hva.bluepumpkin.server.servlets;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.ejb.CreateException;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import vn.hva.bluepumpkin.Constants;
import vn.hva.bluepumpkin.common.dto.EventDTO;
import vn.hva.bluepumpkin.common.dto.UserDTO;
import vn.hva.bluepumpkin.common.util.ServiceLocator;
import vn.hva.bluepumpkin.ejb.session.event.EventFacadeRemote;
import vn.hva.bluepumpkin.ejb.session.event.EventFacadeRemoteHome;
import vn.hva.bluepumpkin.ejb.session.event.TEventPrizeFacadeRemote;
import vn.hva.bluepumpkin.ejb.session.event.TEventPrizeFacadeRemoteHome;
import vn.hva.bluepumpkin.exception.ServerValidationException;
import vn.hva.bluepumpkin.util.ValidatorUtils;

/**
 *
 * @author Leung
 */
public class ManageEvent extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Get action param
        String action = request.getParameter("action");
        String message = "";
        //Get the client's Locale
        Locale locale = request.getLocale();
        ResourceBundle bundle = ResourceBundle.getBundle("vn.hva.bluepumpkin.BluepumpkinResources", locale);

        if (action.equalsIgnoreCase("addWinner")) {
            addWinners(request, response);
        } else if (action.equalsIgnoreCase("updateStatus")) {
            updateStatus(request, response);
        } else {
            InsertUpdate(request, response, action);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void InsertUpdate(HttpServletRequest request, HttpServletResponse response, String action) {
        // Get params
        String eventname = null,
                typeid = null,
                begindate = null,
                enddate = null,
                details = null,
                numberofwinners = null,
                image = null,
                status = null,
                eventid = null;
        try {
            // first check if the upload request coming in is a multipart request
            boolean isMultipart = FileUpload.isMultipartContent(request);

            DiskFileUpload upload = new DiskFileUpload();

            // parse this request by the handler
            // this gives us a list of items from the request
            List items = null;
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException ex) {
                ex.printStackTrace();
            }

            Iterator itr = items.iterator();

            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();

                // check if the current item is a form field or an uploaded file
                if (item.isFormField()) {

                    // get the name of the field
                    String fieldName = item.getFieldName();
                    if(fieldName.equals("eventid")){
                        eventid = item.getString();
                    }else if(fieldName.equals("eventname")){
                        eventname = item.getString();
                    }else if(fieldName.equals("typeid")){
                        typeid = item.getString();
                    }else if(fieldName.equals("begindate")){
                        begindate = item.getString();
                    }else if(fieldName.equals("enddate")){
                        enddate = item.getString();
                    }else if(fieldName.equals("details")){
                        details = item.getString();
                    }else if(fieldName.equals("numberofwinners")){
                        numberofwinners = item.getString();
                    }else if(fieldName.equals("status")){
                        status = item.getString();
                    }
                } else {
                    // the item must be an uploaded file save it to disk. Note that there
                    // seems to be a bug in item.getName() as it returns the full path on
                    // the client's machine for the uploaded file name, instead of the file
                    // name only. To overcome that, I have used a workaround using
                    // fullFile.getName().
                    File fullFile = new File(item.getName());
                    SimpleDateFormat format = new SimpleDateFormat("ddMMyy_hhmmss");
                    image =  format.format(new Date())+fullFile.getName();
                    File savedFile = new File(getServletContext().getRealPath("")+"/images/event/",
                           image);
                    try {
                        item.write(savedFile);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
            // Get EventFascade remote home interface
            EventFacadeRemoteHome eventFacade = (EventFacadeRemoteHome) ServiceLocator.getEjbRemoteHome("java:EventFacade",
                    EventFacadeRemoteHome.class);
            // Get EventFascade remote interface
            EventFacadeRemote eventFacadeRemote = eventFacade.create();
            String message = "";

            // Peform validation
            boolean isValid = validateEventForm(request, eventname, details, status, begindate, enddate, image, typeid, numberofwinners);
            if (isValid) {
                // validation succeed
                // process
                DateFormat df = new SimpleDateFormat(Constants.DATE_FORMAT);
                // Insert or Update
                if (action.equalsIgnoreCase("update")) {
                    // Execute update event
                    //String eventid = request.getParameter("eventid");
                    boolean success = eventFacadeRemote.updateEvent(Integer.parseInt(eventid), eventname, Integer.parseInt(typeid), df.parse(begindate), df.parse(enddate), details, Integer.parseInt(numberofwinners), image, Boolean.parseBoolean(status));
                    if (success) {
                        message = "Update success";
                    } else {
                        message = "Update failed";
                    }
                } else if (action.equalsIgnoreCase("insert")) {
                    String username = ((UserDTO) request.getSession().getAttribute("user")).getUsername();
                    // Execute insert new event
                    EventDTO newEvent = eventFacadeRemote.addNewEvent(eventname, Integer.parseInt(typeid), df.parse(begindate), df.parse(enddate), details, username, Integer.parseInt(numberofwinners), image, Boolean.parseBoolean(status));
                    if (newEvent != null) {
                        message = "Insert success";
                    } else {
                        message = "Insert failed";
                    }
                }
                response.sendRedirect(Constants.ADMIN_URL + "manageevent.jsp?mess=" + message);
                return;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ParseException ex) {
            ex.printStackTrace();
        } catch (ServerValidationException ex) {
            ex.printStackTrace();
        } catch (NamingException ex) {
            ex.printStackTrace();
        } catch (CreateException ex) {
            ex.printStackTrace();
        }
    }

    private void updateStatus(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/xml;charset=UTF-8");

        {
            PrintWriter out = null;

            try {
                out = response.getWriter();
                EventFacadeRemoteHome eventFacade = (EventFacadeRemoteHome) ServiceLocator.getEjbRemoteHome("java:EventFacade",
                        EventFacadeRemoteHome.class);
                EventFacadeRemote eventFacadeRemote = eventFacade.create();
                String eventid = request.getParameter("eventid");
                EventDTO rs = eventFacadeRemote.getEvent(Integer.parseInt(eventid));
                if (rs != null) {
                    boolean success = eventFacadeRemote.updateEventStatus(rs.getEventid(), (rs.getStatus()) ? false : true);
                    returnResult(out, success, "updateStatus");
                } else {
                    returnResult(out, false, "The Event not found");
                }
            } catch (IOException ex) {
                ex.printStackTrace();

            } catch (CreateException ex) {
                ex.printStackTrace();

            } catch (NamingException ex) {
                ex.printStackTrace();

            } finally {
                out.close();

            }
        }
    }

    private void addWinners(HttpServletRequest request, HttpServletResponse response) {
        int eventid = Integer.parseInt(request.getParameter("eventid"));
        // Get the event object need to change status
        TEventPrizeFacadeRemoteHome tvpRemoteHome;
        try {
            tvpRemoteHome = (TEventPrizeFacadeRemoteHome) ServiceLocator.getEjbRemoteHome("java:TEventPrizeFacadeSB", TEventPrizeFacadeRemoteHome.class);
            TEventPrizeFacadeRemote tvpRemote = tvpRemoteHome.create();
            String[] userids = request.getParameterValues("userids");
            String[] scores = request.getParameterValues("scores");
            for (int i = 0; i < userids.length; i++) {
                tvpRemote.addWinner(eventid, Integer.parseInt(userids[i]), Float.parseFloat(scores[i]));
            }
        } catch (CreateException ex) {
            ex.printStackTrace();
        } catch (RemoteException ex) {
            ex.printStackTrace();
        } catch (NamingException ex) {
            ex.printStackTrace();
        }
    }

    private boolean validateEventForm(HttpServletRequest request, String eventname, String details,
            String status, String begindate, String enddate, String image, String typeid, String numberofwinners) {
        ArrayList errs = new ArrayList();
        Locale locale = request.getLocale();
        ResourceBundle bundle = ResourceBundle.getBundle("vn.hva.bluepumpkin.BluepumpkinResources", locale);

        if (eventname.trim().length() < Constants.MIN_LENGTH) {
            // validate eventname
            errs.add(bundle.getString("evt.err_eventname") + "\n");

        }
        if (typeid.trim().length() == 0 && !ValidatorUtils.tryParseInteger(typeid)) {
            // validate event type
            errs.add(bundle.getString("evt.err_typeid") + "\n");
        }
        if (!ValidatorUtils.checkDate(begindate, Constants.DATE_FORMAT)) {
            // validate begin date
            errs.add(bundle.getString("evt.err_begindate") + "\n");
        }
        if (!ValidatorUtils.checkDate(enddate, Constants.DATE_FORMAT)) {
            // validate end date
            errs.add(bundle.getString("evt.err_enddate") + "\n");
        }
        if (details == null || details.trim().length() < 50) {
            // validate event details
            errs.add(bundle.getString("evt.err_details") + "\n");
        }
        if (!ValidatorUtils.tryParseInteger(numberofwinners) || Integer.parseInt(numberofwinners) <= 0 || Integer.parseInt(numberofwinners) > Constants.MAX_NUMBEROFWINNERS) {
            errs.add(bundle.getString("evt.err_numofwinners") + "\n");
        }
        if (image == null || image.trim().length() == 0) {
            errs.add(bundle.getString("evt.err_image") + "\n");
        }
        if (status == null || status.trim().length() == 0) {
            errs.add(bundle.getString("evt.err_status") + "\n");
        }
        if (errs.size() == 0) {
            return true;

        } else {
            request.setAttribute("error", "True");
            request.setAttribute("err_messages", errs);
            return false;
        }
    }

    public void returnResult(PrintWriter out, boolean rs, String note) {
        out.println("<root>");
        out.println("<result>" + rs + "</result>");
        out.println("<note><![CDATA[" + note + "]]></note>");
        out.println("</root>");
    }
}
